package webapi

import (
	"MqttCloudProtocolServer/publiclib/dbcontrol"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/wonderivan/logger"
)

//UserLoginService 网关服务器注册API类。注册控制台
type UserLoginService struct {
	base ServiceBase
}

//Regist 注册
func (_this *UserLoginService) Regist(mux *http.ServeMux) {
	_this.base.Regist(mux)
	_this.base.path += "login"
	_this.base.HandleRegist("checkLogin", _this.checkLogin)
	_this.base.HandleRegist("checkMqttClientID", _this.checkMqttClientID)
}

//AddGateway 增加一个网关连接请求
func (_this *UserLoginService) checkLogin(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()
	if len(vars) > 0 {
		user := GetParam(vars, "user")
		password := GetParam(vars, "password")
		control := dbcontrol.CreateUserconfControl()
		if control == nil {
			logger.Alert("无法获取数据库控制器")
			fmt.Fprintln(w, "Failed")
		}
		if err := control.FindByName(user); err != nil || control.Data == nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
		}
		//bytes := md5.Sum([]byte(password))
		//password = string(bytes[:])
		if control.Data != nil && password == control.Data.Password {
			bytes2, err := json.Marshal(control.Data)
			if err != nil {
				logger.Alert(err)
				fmt.Fprintln(w, "Failed")
			}
			logger.Info(control.Data.Name + ":login")
			fmt.Fprintln(w, string(bytes2[:]))
		} else {
			fmt.Fprintln(w, "Failed")
		}
	}
}

//AddGateway 增加一个网关连接请求
func (_this *UserLoginService) checkMqttClientID(w http.ResponseWriter, r *http.Request) {
	//clientid=%c,username=%u,password=%P
	//w.WriteHeader(402)

	vars := r.URL.Query()
	if len(vars) > 0 {
		clientid := GetParam(vars, "clientid")
		user := GetParam(vars, "username")
		password := GetParam(vars, "password")
		if clientid == "super" {
			w.WriteHeader(200)
		} else {
			w.WriteHeader(402)
		}
		fmt.Fprintln(w, "clientid="+clientid+"\\r\\nuser="+user+"\\r\\npassword="+password)
	}
}
